<template>
  <view class="container">
    <!-- 顶部提示 -->
    <view class="alert">救援服务暂不支持高速救援，高速救援请查看【警务求助】</view>
	<view class="status-container" v-if="orderStatus !== 0">
		<text v-if="orderStatus === 1">正在呼叫中...</text>
	    <text v-if="orderStatus === 2" class="accepted-status">商家已接单</text>
	</view>
    <!-- 地图容器 -->
    <view class="map-container">
      <map 
        id="myMap"
        :latitude="latitude" 
        :longitude="longitude"
        :markers="markers"
        :show-location="true"
        style="width: 100%; height: 300px;">
      </map>
    </view>

    <!-- 服务类型 -->
    <view class="service-tabs">
      <text 
        v-for="item in services" 
        :key="item.type"
        :class="['tab-item', activeType === item.type ? 'active' : '']"
        @click="handleService(item.type)">
        {{item.label}}
      </text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <view class="form-item"  style="display: flex; align-items: center;">
        <text class="label">位置：</text>
        <input v-model="formData.location" placeholder="请输入当前位置"/>
      </view>
      <view class="form-item">
        <text class="label">求助人：</text>
        <input v-model="formData.name"  disabled/>
      </view>
      <view class="form-item">
        <text class="label">联系方式：</text>
        <input v-model="formData.phone" type="number"  disabled/>
      </view>
      <view class="form-item">
        <text class="label">车牌：</text>
        <input v-model="formData.carNumber" placeholder="请输入车牌号"/>
      </view>
	  
	  <view class="form-item">
	      <text class="label">车辆类型：</text>
	      <picker 
	        mode="selector" 
	        :range="vehicleOptions" 
	        range-key="label"
	        @change="handleVehicleChange">
	        <input 
	          :value="selectedVehicleLabel" 
	          placeholder="请选择车辆类型"
	          disabled
	          class="picker-input"/>
	      </picker>
	    </view>
	  
	   <view class="form-item">
	        <text class="label">情况描述：</text>
	        <textarea 
	          v-model="formData.description" 
	          placeholder="请描述车辆具体情况"
	          class="description-input"
	        />
	      </view>
      <!-- 拖车终点 -->
      <view class="form-item" v-if="activeType === 'trailer'">
        <text class="label">终点：</text>
        <input v-model="formData.destination" placeholder="请输入拖车终点"/>
      </view>
    </view>

    <!-- 底部操作 -->
    <view class="action-bar">
      <view class="emergency-contacts">
        <text>交通事故：122</text>
        <text>火警：119</text>
        <text>急救中心：120</text>
        <text>公安报警：110</text>
      </view>
      <button class="call-btn" @click="submitRescue">呼叫救援</button>
      <text class="record-link" @click="goToRecords">救援记录></text>
    </view>
  </view>
</template>

<script setup>
	
import { ref, reactive, onMounted ,computed ,onUnmounted} from 'vue'
import dayjs from 'dayjs'

// 响应式数据
const latitude = ref(35.2156)
const longitude = ref(113.2415)
const memberId = ref("")
const orderStatus = ref(0) // 0-不显示 1-呼叫中 2-已接单
let pollTimer = null
const activeType = ref('power')
const markers = ref([{
  id: 1,
  latitude: latitude.value,
  longitude: longitude.value,
  iconPath: '/static/weizhi.png',
  width: 40,
  height: 40
}])

const formData = reactive({
  location: '',
  name: '',
  phone: '',
  carNumber: '',   //车牌号

  description: '',   //情况说明
  destination: '',
  vehicleModel: '',//车辆类型
  orderStatus: ''   //订单状态
})

const services = ref([
  { type: 'power', label: '搭电' },
  { type: 'tire', label: '换胎' },
  { type: 'trailer', label: '拖车' }
])

// 车辆类型选项
const vehicleOptions = ref([
  { label: '小客车', value: 1 },
  { label: '轻型货车', value: 2 },
  { label: '重型货车', value: 3 },
  { label: '跑车', value: 4 },
  { label: '赛车', value: 5 }
])

// 显示选中的车辆类型标签
const selectedVehicleLabel = computed(() => {
  return vehicleOptions.value.find(
    item => item.value === formData.vehicleModel
  )?.label || ''
})

// 处理选择事件
const handleVehicleChange = (e) => {
  const index = e.detail.value
  formData.vehicleModel = vehicleOptions.value[index].value
}



const serviceMap = {
  power: 1,
  tire: 2,
  trailer: 3
}

// 会员信息请求
const fetchMemberInfo = async () => {
  try {
    const res = await uni.request({
      url: `http://localhost:9587/rescueTask/${Number(memberId.value)}`,
      method: 'GET',
      header: { 'Authorization': uni.getStorageSync('token') }
    })
    if(res.data.code === 200) {
      formData.name = res.data.data.member?.memberName
      formData.phone = res.data.data.member?.phone
    }
  } catch (e) {
    console.error('获取会员信息失败:', e)
  }
}

// 提交救援请求
const submitRescue = async () => {
  const rescueType = serviceMap[activeType.value] || 0
  
   if(isNaN(Number(memberId.value))) {
      return uni.showToast({ title: '用户ID格式错误', icon: 'none' })
    }
	
  const params = {
    rescueType,
    rescueLocation: formData.location,
    applyTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
	memberId: Number(memberId.value),
	destination:formData.destination,
    vehicleNumber: formData.carNumber,
    ext2: latitude.value,
    ext3: longitude.value,
    situationExplanation: formData.description,
	orderStatus:1,
	vehicleModel:formData.vehicleModel,
	mqConfig: {
	    initialRange: 1,        // 初始范围1km
	    maxRetryRange: 3,       // 最大扩展范围3km
	    retryInterval: 10000    // 重试间隔10秒
	},
	geolocation: {            // 结构化地理信息
	    latitude: latitude.value,
	    longitude: longitude.value,
	    coordinateSystem: 'GCJ-02' // 使用国测局坐标系
	}
  }

  try {
    const res = await uni.request({
      url: 'http://localhost:9587/rescueTask',
      method: 'POST',
      header: { 
        'Content-Type': 'application/json',
        'X-MQ-Client': 'uniapp/1.0' // 添加自定义头标识
      },
      data: params
    })


	// 增加MQ状态判断
	if(res.data.code === 200 && res.data.data.mqStatus === 'SENT') {
	    orderStatus.value = 1
	    startOrderPolling()
	    trackMQEvent(res.data.data.messageId) // 消息追踪
	}
    if(res.data.code === 200) {
      uni.showToast({ title: '救援提交成功' })
    } else {
      uni.showToast({ title: '请求失败', icon: 'none' })
    }
  } catch (e) {
    uni.showToast({ title: '网络请求失败', icon: 'none' })
  }
}

const trackMQEvent = (messageId) => {
  uni.$on('mq-status-update', (data) => {
    if(data.messageId === messageId) {
      switch(data.status) {
        case 'DELIVERED':
          console.log('消息已进入队列')
          break
        case 'EXPAND_RANGE':
          uni.showToast({
            title: `搜索范围扩大至${data.range}km`,
            icon: 'none'
          })
          break
        case 'FINAL_RETRY':
          handleFinalRetry(messageId)
          break
      }
    }
  })
}

// 错误处理增强
const handleMQError = (error) => {
  const errorMap = {
    NO_AVAILABLE_MERCHANTS: {
      title: '附近无可用商家',
      action: () => showExpansionMap()
    },
    MQ_SERVER_ERROR: {
      title: '服务繁忙，请重试',
      action: () => retrySubmission()
    }
  }
  
  const handler = errorMap[error.code] || {
    title: '请求失败',
    action: () => {}
  }
  
  uni.showModal({
    title: '系统提示',
    content: handler.title,
    success: res => {
      if(res.confirm) handler.action()
    }
  })
}

// 扩展地图显示
const showExpansionMap = () => {
  uni.navigateTo({
    url: `/pages/map-expansion/map-expansion?lat=${latitude}&lng=${longitude}`
  })
}

// 新增轮询方法
const startOrderPolling = () => {
  pollTimer = setInterval(async () => {
    try {
      const res = await uni.request({
        url: `http://localhost:9587/rescueTask/${Number(memberId.value)}`,
        method: 'GET',
        header: { 'Authorization': uni.getStorageSync('token') }
      })
      
      if(res.data.data.orderStatus === 2) {
        orderStatus.value = 2
        clearInterval(pollTimer)
      }
    } catch(e) {
      console.error('轮询失败:', e)
    }
  }, 3000) // 每3秒请求一次
}


// 生命周期
onMounted(() => {
	 memberId.value = uni.getStorageSync('memberId') || ''
	 fetchMemberInfo() 
     initLocation()
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if(pollTimer) clearInterval(pollTimer)
})

// 定位逻辑
const initLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: res => {
      latitude.value = res.latitude
      longitude.value = res.longitude
      markers.value[0].latitude = res.latitude
      markers.value[0].longitude = res.longitude
    }
  })
}

const handleService = (type) => {
  activeType.value = type
  if(type !== 'trailer') formData.destination = ''
}

// 跳转救援记录
const goToRecords = () => {
	console.log(11)
  // uni.navigateTo({ url: '/pages/rescue-records/rescue-records' })
}
</script>
<style lang="scss" scoped>
.container {
  background: #f8f8f8;
  min-height: 100vh;
}
.status-container {
  padding: 20rpx;
  text-align: center;
  font-size: 32rpx;
}
.accepted-status {
  color: #09bb07;
  font-weight: bold;
}
.alert {
  padding: 20rpx;
  background: #ffecec;
  color: #eb5757;
  font-size: 24rpx;
}

.map-container {
  padding: 20rpx;
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.service-tabs {
  display: flex;
  justify-content: space-around;
  padding: 30rpx 0;
  .tab-item {
    font-size: 32rpx;
    color: #666;
    padding: 15rpx 40rpx;
    border-radius: 8rpx;
    &.active {
      color: #eb5757;
      font-weight: 500;
      background: #ffecec;
    }
  }
}

.form-container {
  margin: 0 20rpx;
  background: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  .form-item {
    margin-bottom: 30rpx;
    .label {
      width: 140rpx;
      display: inline-block;
      color: #333;
      font-size: 28rpx;
    }
    input {
      display: inline-block;
      width: calc(100% - 160rpx);
      border-bottom: 1rpx solid #eee;
      
      font-size: 28rpx;
    }
  }
}

.action-bar {
  margin-top: 40rpx;
  padding: 30rpx;
  background: #fff;
  .emergency-contacts {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    font-size: 24rpx;
    color: #666;
    margin-bottom: 40rpx;
  }
  .call-btn {
    background: #ff8038;
    color: #fff;
    border-radius: 50rpx;
    font-size: 32rpx;
  }
  .record-link {
    display: block;
    text-align: center;
    color: #007aff;
    margin-top: 30rpx;
  }
}

.description-input {
  width: 100%;
  height: 200rpx;
  padding: 20rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  margin-top: 20rpx;
}

.picker-input {
  border-bottom: 1rpx solid #eee;
  
  font-size: 28rpx;
  color: #333;
}
</style>